<template>
  <div class="menuBtnGroups">
    <div class="head_btn" @click="initCreateForm">
      <el-tooltip effect="dark" content="初始化" placement="bottom">
        <i class="el-icon-s-grid"></i>
      </el-tooltip>
    </div>
    <div :class="[dataJson.rows.length == 0 ? 'disable' : '', 'head_btn']" @click="handleSave">
      <el-tooltip effect="dark" content="保存 ctrl+s" placement="bottom">
        <i class="el-icon-document"></i>
      </el-tooltip>
    </div>
    <div class="head_btn" @click="handlePreview">
      <el-tooltip effect="dark" content="预览" placement="bottom">
        <i class="el-icon-view"></i>
      </el-tooltip>
    </div>
    <div :class="[histroyIndex <= 1 ? 'disable' : '', 'head_btn']" @click="handleUndo">
      <el-tooltip effect="dark" content="撤销 ctrl+z" placement="bottom">
        <i class="el-icon-refresh-left"></i>
      </el-tooltip>
    </div>
    <div :class="[histroyIndex == histroyData.length ? 'disable' : '', 'head_btn']" @click="handleRedo">
      <el-tooltip effect="dark" content="恢复 ctrl+y" placement="bottom">
        <i class="el-icon-refresh-right"></i>
      </el-tooltip>
    </div>
    <div class="toolbar-divider"></div>

    <div class="head_btn">
      <el-tooltip effect="dark" content="字号" placement="bottom">
        <el-dropdown class="toolbar-fontsize" szie="mini" trigger="click" @command="(value) => handleChangeProperties(value, 'font-size')">
          <span class="el-dropdown-link">{{ tooltip.fontSize }}<i class="el-icon-arrow-down el-icon--right"></i> </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="item" v-for="item in fontSizeList" :key="item">{{ item }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-tooltip>
    </div>
    <div class="head_btn" @click="handleFlag('font-weight')">
      <el-tooltip effect="dark" content="加粗" placement="bottom">
        <svg t="1710485414947" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7569" width="16" height="16">
          <path
            d="M521.1 530.3h-174V457h174.1c65.8 0 119.1-53.3 119.1-119.1S587 218.8 521.2 218.8H347.1v-73.3h174.1c106.3-0.2 192.6 85.9 192.7 192.2 0.1 106.2-85.9 192.5-192.2 192.6h-0.6z"
            fill="#fff"
            p-id="7570"
          ></path>
          <path
            d="M576.2 878.6H347.1v-73.3h229.1c75.9 0 137.5-61.5 137.5-137.5 0-75.9-61.5-137.5-137.5-137.5H347.1V457h229.1C692.6 457 787 551.4 787 667.8s-94.4 210.8-210.8 210.8z"
            fill="#fff"
            p-id="7571"
          ></path>
          <path d="M383.7 878.6H237.1v-73.3h73.3V218.8h-73.3v-73.3h146.6v733.1z" fill="#fff" p-id="7572"></path>
        </svg>
      </el-tooltip>
    </div>
    <div class="head_btn" @click="handleFlag('font-style')">
      <el-tooltip effect="dark" content="倾斜" placement="bottom">
        <svg t="1710485242671" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4996" width="16" height="16">
          <path
            d="M597.333333 853.333333H341.333333a42.666667 42.666667 0 0 1 0-85.333333h82.218667l90.282667-512H426.666667a42.666667 42.666667 0 1 1 0-85.333333h256a42.666667 42.666667 0 0 1 0 85.333333h-82.218667l-90.282667 512H597.333333a42.666667 42.666667 0 0 1 0 85.333333z"
            fill="#fff"
            p-id="4997"
          ></path>
        </svg>
      </el-tooltip>
    </div>
    <div class="head_btn" @click="handleFlag('text-decoration')">
      <el-tooltip effect="dark" content="下划线" placement="bottom">
        <svg t="1710485368787" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6334" width="16" height="16">
          <path
            d="M497.792 682.666667c105.898667 0 192-90.197333 192-201.130667V213.333333h-80v268.202667c0 64.682667-50.261333 117.333333-112 117.333333-61.781333 0-112-52.650667-112-117.333333V213.333333H305.792v268.202667c0 110.933333 86.058667 201.130667 192 201.130667zM305.792 725.333333v85.333334h384v-85.333334z"
            fill="#fff"
            p-id="6335"
          ></path>
        </svg>
      </el-tooltip>
    </div>
    <div class="head_btn">
      <el-tooltip effect="dark" content="字体颜色" placement="bottom">
        <el-color-picker size="mini" v-model="tooltip.color" show-alpha @change="(value) => handleChangeProperties(value, 'color')"></el-color-picker>
      </el-tooltip>
    </div>
    <div class="head_btn">
      <el-tooltip effect="dark" content="填充颜色" placement="bottom">
        <el-color-picker
          class="toolbar-bgcolor"
          size="mini"
          v-model="tooltip.bgcolor"
          show-alpha
          @change="(value) => handleChangeProperties(value, 'background-color')"
        ></el-color-picker>
      </el-tooltip>
    </div>
    <div class="toolbar-divider"></div>
    <el-dropdown @command="handleCommand">
      <span class="el-dropdown-link">
        <div class="head_btn">
          <el-tooltip effect="dark" content="对齐方式" placement="bottom">
            <svg
              t="1714008585841"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="6061"
              id="mx_n_1714008585842"
              width="16"
              height="16"
            >
              <path
                d="M80 192A48 48 0 0 1 128 144h768a48 48 0 0 1 0 96H128A48 48 0 0 1 80 192z m192 320A48 48 0 0 1 320 464h384a48 48 0 0 1 0 96H320A48 48 0 0 1 272 512zM128 784a48 48 0 0 0 0 96h768a48 48 0 0 0 0-96H128z"
                fill="#ffffff"
                p-id="6062"
              ></path>
            </svg>
          </el-tooltip>
        </div>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="left">
          <div class="head_btn">
            <svg
              t="1713508665968"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="1903"
              id="mx_n_1713508665969"
              width="16"
              height="16"
            >
              <path d="M96 128h832v96H96zM96 576h832v96H96zM96 352h576v96H96zM96 800h576v96H96z" p-id="1904" fill="#000"></path>
            </svg>
          </div>
        </el-dropdown-item>
        <el-dropdown-item command="center">
          <div class="head_btn">
            <svg t="1713508717842" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2838" width="16" height="16">
              <path d="M96 128h832v96H96zM96 576h832v96H96zM224 352h576v96H224zM224 800h576v96H224z" p-id="2839" fill="#000"></path>
            </svg>
          </div>
        </el-dropdown-item>
        <el-dropdown-item command="right">
          <div class="head_btn">
            <svg
              t="1713508768948"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="4016"
              id="mx_n_1713508768948"
              width="16"
              height="16"
            >
              <path d="M96 128h832v96H96zM96 576h832v96H96zM352 352h576v96H352zM352 800h576v96H352z" p-id="4017" fill="#000"></path>
            </svg>
          </div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <div class="toolbar-divider"></div>
    <div class="head_btn" @click="handleHeadUpload">
      <el-tooltip effect="dark" content="上传excel" placement="bottom">
        <i class="el-icon-upload2"></i>
      </el-tooltip>
      <input type="file" style="visibility: hidden; width: 0" ref="inputFileIcon" @change="handleUpload" />
    </div>
    <div class="head_btn" @click="handlePrint">
      <el-tooltip effect="dark" content="打印设置" placement="bottom">
        <i class="el-icon-printer"></i>
      </el-tooltip>
    </div>
    <div class="toolbar-divider"></div>
    <div class="head_btn" @click="handleLookCode">
      <el-tooltip effect="dark" content="查看代码" placement="bottom">
        <i class="el-icon-view"></i>
      </el-tooltip>
    </div>
    <div class="head_btn" @click="handleDataCheck">
      <el-tooltip effect="dark" content="数据检测" placement="bottom">
        <i class="el-icon-check"></i>
      </el-tooltip>
    </div>

    <!-- 初始化表格 -->
    <el-dialog width="500px" title="初始化表格" :visible.sync="initTable.visible" :modal-append-to-body="true" :append-to-body="true">
      <el-form ref="ruleForm" :inline="false" :model="initTable" label-width="120px" size="mini" :rules="rules">
        <el-form-item label="行数" prop="rows">
          <el-input-number v-model="initTable.rows" :min="1" :precision="0" controls-position="right"> </el-input-number>
        </el-form-item>
        <el-form-item label="列数" prop="columns">
          <el-input-number v-model="initTable.columns" :min="1" :precision="0" controls-position="right"> </el-input-number>
        </el-form-item>
        <el-form-item label="单元格宽度" prop="cellWidth">
          <el-input-number v-model="initTable.cellWidth" :min="10" controls-position="right"> </el-input-number>
        </el-form-item>
        <el-form-item label="单元格高度" prop="cellHeight">
          <el-input-number v-model="initTable.cellHeight" :min="10" controls-position="right"> </el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="cancelCreateForm">取 消</el-button>
        <el-button size="small" type="primary" icon="el-icon-circle-plus-outline" @click="submitCreateForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新建保存 输入检验模板名称和类型 -->
    <el-dialog width="500px" title="新增检验模板" :visible.sync="template.visible" :modal-append-to-body="true" :append-to-body="true">
      <avue-form :option="template.option" v-model="template.form" @submit="submitTemplate" />
    </el-dialog>

    <!-- 预览前置条件 -->
    <el-dialog
      custom-class="previewDialog"
      title="预览"
      width="30%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="previewDialog.visible"
      :fullscreen="false"
      :before-close="handleClose"
    >
      <avue-form ref="form" v-model="previewDialog.form" :option="previewDialog.option" @submit="handleSubmit"> </avue-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleCancel">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="$refs.form.submit()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 实时预览弹框 -->
    <el-dialog
      custom-class="livePreviewDialog"
      title="预览"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="livePreviewDialog.visible"
      :fullscreen="true"
      :before-close="handleClose"
      @open="handleLivePreviewOpen"
    >
      <livePreview ref="live" :liveParams="liveParams"></livePreview>
    </el-dialog>

    <el-dialog v-if="codeDialog.visible" custom-class="codeDialog" title="查看代码" width="90%" append-to-body :close-on-click-modal="false" :visible.sync="codeDialog.visible">
      <!-- <MonacoEditor :code.sync="codeDialog.code" :opts="codeDialog.options" @contentChange="contentChange"></MonacoEditor> -->
      <!-- <el-input type="textarea" v-model="codeDialog.code" :disabled="false" :autosize="{ minRows: 25, maxRows: 25 }"></el-input> -->
      <div class="container">
        <vue-json-editor mode="code" lang="zh" v-model="codeDialog.code" :expandedOnStart="true" :showBtns="false"></vue-json-editor>
      </div>
      <div class="operateBtn">
        <!-- <el-button type="success" icon="el-icon-copy-document" size="small" @click="handleCopyCode">复制代码</el-button> -->
        <!-- <el-button type="success" icon="el-icon-download" size="small" @click="handleImportCode">导入代码</el-button> -->
      </div>
    </el-dialog>

    <!-- 打印设置 -->
    <el-dialog width="500px" title="打印设置" :visible.sync="printDialog.visible" :modal-append-to-body="true" :append-to-body="true">
      <avue-form ref="printForm" :option="printDialog.option" v-model="printDialog.form" @submit="handleSubmitPrint" />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="printDialog.visible = false">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="$refs.printForm.submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fontSizeList, letters } from './data.js';
import { isClickSameCell, getBoxAreaData, pageSizeInPixels } from './util.js';
import { mapGetters, mapState } from 'vuex';
import { add } from '@/api/designer/apaasList';
import paramVue from '../system/param.vue';
import livePreview from './livePreview.vue';
import * as XLSX from 'xlsx';
import vueJsonEditor from 'vue-json-editor';
export default {
  components: {
    livePreview,
    vueJsonEditor
  },
  inject: ['reload'],
  data() {
    return {
      codeDialog: {
        visible: false,
        code: '',
        options: {
          readOnly: false
        }
      },
      liveParams: {},
      livePreviewDialog: {
        visible: false
      },
      previewDialog: {
        visible: false,
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 120,
          column: [] // 取配置的第一个api
        }
      },
      template: {
        visible: false,
        form: {
          name: '',
          type: '',
          id: ''
        },
        option: {
          labelWidth: 70,
          submitBtn: true,
          emptyBtn: true,
          labelWidth: 120,
          column: [
            {
              label: '检验模板名称',
              prop: 'name',
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请选择检验模板名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '检验模板类型',
              prop: 'type',
              span: 24,
              type: 'select',
              search: true,
              dicUrl: '/api/blade-system/dict/dictionary?code=QC',
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              rules: [
                {
                  required: true,
                  message: '请选择检验模板类型',
                  trigger: 'change'
                }
              ]
            }
          ]
        }
      },
      printDialog: {
        visible: false,
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 60,
          column: [
            {
              label: '尺寸',
              prop: 'format',
              span: 12,
              type: 'select',
              value: 'a4',
              dicData: [
                {
                  label: 'A0',
                  value: 'a0'
                },
                {
                  label: 'A1',
                  value: 'a1'
                },
                {
                  label: 'A2',
                  value: 'a2'
                },
                {
                  label: 'A3',
                  value: 'a3'
                },
                {
                  label: 'A4',
                  value: 'a4'
                },
                {
                  label: 'A5',
                  value: 'a5'
                },
                {
                  label: 'B0',
                  value: 'b0'
                },
                {
                  label: 'B1',
                  value: 'b1'
                },
                {
                  label: 'B2',
                  value: 'b2'
                },
                {
                  label: 'B3',
                  value: 'b3'
                },
                {
                  label: 'B4',
                  value: 'b4'
                },
                {
                  label: 'B5',
                  value: 'b5'
                }
              ],
              change: ({ value }) => {
                this.changeFormat(value);
              },
              rules: [
                {
                  required: true,
                  message: '请选择尺寸',
                  trigger: 'change'
                }
              ]
            },
            {
              label: '方向',
              prop: 'orientation',
              span: 12,
              type: 'select',
              value: 'portrait',
              dicData: [
                // {
                //   label: '横向',
                //   value: 'landscape'
                // },
                {
                  label: '纵向',
                  value: 'portrait'
                }
              ],
              rules: [
                {
                  required: true,
                  message: '请选择方向',
                  trigger: 'change'
                }
              ]
            },
            {
              label: '宽',
              prop: 'width',
              disabled: true,
              span: 12
            },
            {
              label: '高',
              prop: 'height',
              disabled: true,
              span: 12
            }
          ]
        }
      },
      tooltip: {
        color: '',
        bgcolor: '',
        fontSize: 12,
        'font-weight': ['bold', 'normal'],
        'font-style': ['italic', 'normal'],
        'text-decoration': ['underline', 'none']
      },
      initTable: {
        visible: false,
        rows: undefined,
        columns: undefined,
        cellWidth: 100,
        cellHeight: 30
      },
      rules: {
        rows: [{ required: true, message: '请输入行数', trigger: 'change' }],
        columns: [{ required: true, message: '请输入列数', trigger: 'change' }],
        cellWidth: [{ required: true, message: '请输入单元格宽度', trigger: 'change' }],
        cellHeight: [{ required: true, message: '请输入单元格高度', trigger: 'change' }]
      },
      startX: '',
      startY: '',
      fontSizeList: fontSizeList
    };
  },
  computed: {
    ...mapState({
      cellInfo: (state) => state.form.cellInfo,
      dataJson: (state) => state.form.dataJson,
      apiJson: (state) => state.form.apiJson,
      submitJson: (state) => state.form.submitJson,
      dictJson: (state) => state.form.dictJson,
      histroyData: (state) => state.form.histroyData,
      histroyIndex: (state) => state.form.histroyIndex,
      baseTableConfig: (state) => state.form.baseTableConfig,
      boxAreaXY: (state) => state.form.boxAreaXY,
      xAxisNum: (state) => state.form.xAxisNum,
      yAxisNum: (state) => state.form.yAxisNum
    }),
    isNotSameCell() {
      return isClickSameCell(this.boxAreaXY.startX, this.boxAreaXY.startY, this.boxAreaXY.endX, this.boxAreaXY.endY);
    }
  },
  methods: {
    // 初始化表单 输入几行几列
    initCreateForm() {
      this.initTable.visible = true;
      this.initTable.rows = undefined;
      this.initTable.columns = undefined;
      this.initTable.cellWidth = 100;
      this.initTable.cellHeight = 30;
    },
    submitCreateForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.initTable.visible = false;
          this.$emit('initForm', this.initTable);
          console.log(this.dataJson);
        }
      });
    },
    cancelCreateForm() {
      this.$refs['ruleForm'].resetFields();
      this.initTable.visible = false;
    },
    handleChangeProperties(value, property) {
      if (property == 'font-size') {
        this.tooltip.fontSize = value;
      } else if (property == 'color') {
        this.tooltip.color = value;
      } else if (property == 'background-color') {
        this.tooltip.bgcolor = value;
      }
      let boxAreaData = this.isNotSameCell ? getBoxAreaData(this.dataJson.rows, this.boxAreaXY) : [this.dataJson.rows[this.cellInfo.y - 1].cells[this.cellInfo.x - 1]];
      boxAreaData.map((item) => {
        this.$set(item.style, property, value);
      });

      if (!this.isNotSameCell) {
        this.$set(this.cellInfo.style, property, value);
      }
    },
    handleCommand(command) {
      let boxAreaData = this.isNotSameCell ? getBoxAreaData(this.dataJson.rows, this.boxAreaXY) : [this.dataJson.rows[this.cellInfo.y - 1].cells[this.cellInfo.x - 1]];
      boxAreaData.map((item) => {
        this.$set(item.style, 'text-align', command);
      });
      if (!this.isNotSameCell) {
        this.$set(this.cellInfo.style, 'text-align', command);
      }
    },
    handleSave() {
      this.$emit('handleSaveData');
    },
    handlePreview() {
      if (this.apiJson && this.apiJson.length > 0 && this.apiJson[0].showQuery) {
        let params = this.apiJson[0].showQuery.parameterDatas;
        if (params && params.length > 0) {
          this.previewDialog.visible = true;
          this.previewDialog.option.column = params.map((item) => {
            return {
              label: item.label,
              prop: item.code,
              span: 24,
              rules: [{ required: true, message: `请输入${item.label}`, trigger: 'blur' }]
            };
          });
        } else {
          this.previewDialog.option.column = [];
          this.livePreviewDialog.visible = true;
          this.liveParams = structuredClone({});
        }
      } else {
        this.previewDialog.option.column = [];
        this.livePreviewDialog.visible = true;
        this.liveParams = structuredClone({});
      }
    },
    handleSubmit(form, done) {
      done();
      let params = {};
      Object.keys(form).forEach((key) => {
        params[key] = form[key];
      });
      this.livePreviewDialog.visible = true;
      console.log('🚀 ~ handleSubmit ~ params:', params);
      this.liveParams = structuredClone(params);
    },
    handleCancel() {
      this.$refs.form.resetForm();
      this.previewDialog.visible = false;
    },
    handleLivePreviewOpen() {
      this.$nextTick(() => {
        if (this.$refs.live) {
          this.$refs.live.handlePreviewApi();
        }
      });
    },
    handleFlag(name) {
      let boxAreaData = this.isNotSameCell ? getBoxAreaData(this.dataJson.rows, this.boxAreaXY) : [this.dataJson.rows[this.cellInfo.y - 1].cells[this.cellInfo.x - 1]];
      let status = boxAreaData.every((item) => {
        return item.style && item.style[name] == this.tooltip[name][0];
      });

      this.handleCellSetStyle(boxAreaData, name, status);
      if (!this.isNotSameCell) {
        this.$set(this.cellInfo.style, name, status ? this.tooltip[name][1] : this.tooltip[name][0]);
      }
    },
    handleCellSetStyle(boxAreaData, name, status) {
      boxAreaData.map((item) => {
        this.$set(item.style, name, status ? this.tooltip[name][1] : this.tooltip[name][0]);
      });
    },
    handleUndo() {
      this.$store.commit('form/undo');
    },
    handleRedo() {
      this.$store.commit('form/redo');
    },
    submitTemplate(form, done) {
      this.dataJson.name = form.name;
      this.dataJson.type = form.type;
      let params = {
        name: form.name,
        type: form.type,
        content: JSON.stringify(this.dataJson),
        apiJson: JSON.stringify(this.apiJson),
        submitJson: JSON.stringify(this.submitJson),
        dictJson: JSON.stringify(this.dictJson)
      };
      console.log(params, 'params');
      add(params)
        .then((res) => {
          this.template.visible = false;
          this.$message.success('保存成功');
          this.$emit('handleAddTemplateSuccess');
        })
        .catch((err) => {})
        .finally(() => {
          done();
        });
    },
    handleLookCode() {
      this.codeDialog.visible = true;
      this.codeDialog.code = structuredClone(this.dataJson);
    },
    handleDataCheck() {
      let result = this.detectMergeCellIssues(this.dataJson.rows);
      if (result.length > 0) {
        console.error(result.join(';'));
      } else {
        console.log('未检测到问题');
      }
    },
    // 1.当单元格hide为false时,不需要mergeCell属性
    // 2.当单元格hide为true时,需要mergeCell属性，并且merge属性必须为[1,1]
    detectMergeCellIssues(data) {
      const issues = {
        missingMergeCell: [],
        unnecessaryMergeCell: [],
        incorrectMerge: []
      };

      data.forEach((row) => {
        row.cells.forEach((cell) => {
          const x = cell.x;
          const y = cell.y;

          if (cell.hide) {
            if (!cell.mergeCell) {
              issues.missingMergeCell.push(`(${x}, ${y})`);
            }
            if (cell.merge && (cell.merge[0] !== 1 || cell.merge[1] !== 1)) {
              issues.incorrectMerge.push(`(${x}, ${y})`);
            }
          } else {
            if (cell.mergeCell) {
              issues.unnecessaryMergeCell.push(`(${x}, ${y})`);
            }
          }
        });
      });

      const result = [];

      if (issues.missingMergeCell.length > 0) {
        result.push(`缺少 mergeCell 属性的单元格: ${issues.missingMergeCell.join(', ')};解决方案: 先拆分再合并。`);
      }
      if (issues.unnecessaryMergeCell.length > 0) {
        result.push(`多余的 mergeCell 属性的单元格: ${issues.unnecessaryMergeCell.join(', ')};解决方案: 移除这些单元格的多余 mergeCell 属性。`);
      }
      if (issues.incorrectMerge.length > 0) {
        result.push(`merge 属性不正确的单元格: ${issues.incorrectMerge.join(', ')};解决方案:可能需要多次的拆分再合并,将这些单元格的 merge 属性设置为 [1, 1]。`);
      }

      return result.length > 0 ? result : [];
    },
    // handleCopyCode() {
    //   let content = JSON.parse(this.codeDialog.code);
    //   this.$message.success('复制成功');
    // },
    handleImportCode() {
      let content = new Function('return ' + JSON.stringify(this.codeDialog.code))();
      this.$store.dispatch('form/saveForm', {
        apiJson: this.apiJson,
        dataJson: content,
        submitJson: this.submitJson,
        dictJson: this.dictJson
      });
      this.$message.success('导入代码成功');
      this.codeDialog.visible = false;
      // this.reload();
    },
    handleHeadUpload() {
      let inputFile = this.$refs.inputFileIcon;
      inputFile.click();
    },
    handleUpload(e) {
      let fileObj = e.target.files[0];
      let fileReader = new FileReader();
      fileReader.readAsArrayBuffer(fileObj);
      fileReader.onload = (evt) => {
        let fileData = evt.target.result;
        const excelDatas = XLSX.read(fileData, {
          type: 'binary'
        });
        let SheetNames = excelDatas.SheetNames[0];
        let excelObj = excelDatas.Sheets[SheetNames];
        let ref = excelObj['!ref'];
        let merges = excelObj['!merges'] || [];
        // "A1:D4"
        let rows = getRows(ref);
        let columns = getColumns(ref);
        let stepRows = Number(ref.split(':')[0].replace(/[^0-9]/gi, '')) - 1;
        let stepColumns = letters.indexOf(ref.split(':')[0].replace(/[^A-Z]/gi, ''));
        let mergeCell = formatterMerges(merges);
        let dataJSON = createDataJson(rows, columns);
        this.$message.success('导入成功');
        console.log(dataJSON, 'dataJSON');
        this.initTable.rows = rows;
        this.initTable.columns = columns;
        this.$store.dispatch('form/setDataJson', {
          id: this.dataJson.id,
          merges: [],
          name: this.dataJson.name,
          printConfig: {},
          rows: dataJSON,
          type: this.dataJson.type,
          tableTotalWidth: columns * 100
        });

        function formatterMerges(data) {
          return data.map((cell) => {
            return {
              x: cell.s.c - stepColumns,
              y: cell.s.r - stepRows,
              merge: [cell.e.r - cell.s.r + 1, cell.e.c - cell.s.c + 1]
            };
          });
        }

        function createDataJson(row, columns) {
          let data = [];
          let startLetter = ref.split(':')[0].replace(/[^A-Z]/gi, '');
          let startLetterIndex = letters.indexOf(startLetter);
          let startNum = Number(ref.split(':')[0].replace(/[^0-9]/gi, ''));

          for (let i = 0; i < row; i++) {
            data.push({
              cells: [],
              height: 30
            });
            for (let j = 0; j < columns; j++) {
              let cellInfo = excelObj[`${letters[startLetterIndex + j]}${startNum + i}`];
              let findMerge = mergeCell.find((item) => item.x == j && item.y == i);
              data[i].cells.push({
                x: j,
                y: i,
                value: cellInfo ? cellInfo.v : '',
                code: cellInfo ? cellInfo.v : '',
                // type: cellInfo ? (cellInfo.t == 's' ? 'text' : 'number') : 'text',
                type: 'text',
                merge: findMerge ? findMerge.merge : [1, 1],
                dicCode: '',
                dicData: [],
                isLock: false,
                isEdit: false,
                apiField: false,
                isForamtter: false,
                url: '',
                dataType: '1',
                dataFormatter: '',
                method: 'post',
                query: '',
                style: {
                  width: findMerge ? findMerge.merge[1] * 100 : 100,
                  height: findMerge ? findMerge.merge[0] * 30 : 30
                },
                eventConfig: {}
              });
            }
          }
          mergeCell.map((item) => {
            // 合并区域其余单元格赋值mergeCelln并将hide:true
            for (let i = item.y; i <= item.y + item.merge[0] - 1; i++) {
              for (let j = item.x; j <= item.x + item.merge[1] - 1; j++) {
                if (i != item.y || j != item.x) {
                  data[i].cells[j].mergeCell = item.x + '-' + item.y;
                  data[i].cells[j].hide = true;
                }
              }
            }
          });
          return data;
        }

        function getRows(data) {
          return data.split(':')[1].replace(/[^0-9]/gi, '') - data.split(':')[0].replace(/[^0-9]/gi, '') + 1;
        }

        function getColumns(data) {
          let startLetter = data.split(':')[0].replace(/[^A-Z]/gi, '');
          let endLetter = data.split(':')[1].replace(/[^A-Z]/gi, '');
          let startIndex = letters.indexOf(startLetter);
          let endIndex = letters.indexOf(endLetter);
          return endIndex - startIndex + 1;
        }
      };
    },
    handleBack() {},
    changeFormat(value) {
      let { width, height } = pageSizeInPixels(value);
      this.printDialog.form.width = width;
      this.printDialog.form.height = height;
    },
    handlePrint() {
      this.printDialog.visible = true;
      this.printDialog.form = structuredClone(this.dataJson.printConfig);
    },
    handleSubmitPrint(form, done) {
      console.log(form, 'form');
      this.$store.commit('form/setPrint', form);
      this.printDialog.visible = false;
      done();
    },
    initToolTip() {
      this.tooltip.fontSize = 12;
      this.tooltip.color = '';
      this.tooltip.bgcolor = '';
    }
  }
};
</script>

<style lang="scss" scoped>
.menuBtnGroups {
  position: absolute;
  top: 40px;
  left: 0;
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  user-select: none;
  background-color: #1d1e1f;
  .head_btn {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      color: #fff;
    }
    &.disable {
      opacity: 0.5;
      pointer-events: none;
    }
    &.active {
      background-color: rgba(0, 0, 0, 0.08);
    }
    .toolbar-fontsize {
      color: #fff;
      white-space: nowrap;
    }
  }
  .toolbar-divider {
    border-right: 1px solid #e0e2e4;
    display: inline-block;
    height: 18px;
    margin: 1px 3px 0;
    vertical-align: middle;
    width: 0;
  }
}
.codeDialog {
  .container {
    ::v-deep {
      /* jsoneditor右上角默认有一个链接,加css去掉 */
      .jsoneditor-poweredBy {
        display: none !important;
      }

      /*修改高度*/
      div.jsoneditor-outer {
        height: 60vh;
      }
      /*修改菜单栏背景颜色,原始背景为蓝色，为了和整体页面风格一致，改为黑色*/
      div.jsoneditor-menu {
        background-color: #000;
        border-bottom: 1px solid #000;
      }

      /*修改输入框边框颜色*/
      div.jsoneditor {
        border: 1px solid #000;
      }
    }
  }
  .operateBtn {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
